﻿#ifndef AUTORESIZINGTEXTBROWSER_H
#define AUTORESIZINGTEXTBROWSER_H

#include <QApplication>
#include <QTextBrowser>
#include <QVBoxLayout>
#include <QWidget>
#include <QTimer>

class AutoResizingTextBrowser : public QTextBrowser
{
    Q_OBJECT
public:
    AutoResizingTextBrowser(QWidget* parent = nullptr) : QTextBrowser(parent)
    {
        connect(this, &QTextBrowser::textChanged, this, &AutoResizingTextBrowser::adjustHeight);
        // 初始时也调整高度
        QTimer::singleShot(0, this, &AutoResizingTextBrowser::adjustHeight);
    }

private slots:
    void adjustHeight()
    {
        document()->setTextWidth(width());
        int docHeight = document()->size().height();
        if (docHeight + frameWidth() * 2 > 300)
            setFixedHeight(300);
        else
        {
            auto _x = frameWidth() * 2;
            setFixedHeight(docHeight + frameWidth() * 2);
        }
    }
};

#endif // AUTORESIZINGTEXTBROWSER_H
